<?php
class News_model extends Model
{
    function __construct()
    {
        parent::__construct();
        $this->load->database();
    }
    public function get_article_list($page=0)
    {
        $this->db->select("*");
        $this->db->from('news');
        $this->db->order_by('id','asc');
        $this->db->limit(5,$page);

        $sql_res = $this->db->get();
        $res = $sql_res->result_array();
        return !empty($res)? $res : 'null' ;
    }

    public function get_article_by_id($id)
    {
        $id = intval($id);
        $last_id = $this->_get_last_id_article();
        if($id<= $last_id && $id >=1)
        {
            $this->db->select("*");
            $this->db->from('news');
            $this->db->where('id',$id);
            $this->db->limit(1);
            $sql_res = $this->db->get();
            $res = $sql_res->result_array();
            $this->_updateArticleHits($id);
        }
        else
        {
            $res = '';
        }
        return !empty($res)? $res[0] : 'null' ;
    }

    private function _updateArticleHits($id)
    {
        $res = $this->db->query("UPDATE `news` SET hits = hits+1 WHERE id = $id");
        return $res;
    }

    private function _get_last_id_article()
    {
        $this->db->from('news');
        $this->db->select_max('id');
        $query = $this->db->get();
        $res = $query->result_array();
        return isset($res[0])? $res[0]['id'] : NULL ;
    }

    public function get_comment_list_by_id($id)
    {
        $id = intval($id);
        $this->db->select("*");
        $this->db->from('article_comments');
        $this->db->where('article_id',$id);
        $this->db->order_by('id','desc');
        $sql_res = $this->db->get();
        $res = $sql_res->result_array();
        return $res;
    }

    public function insert_new_comment($data_to_insert = array())
    {
        $this->db->insert('article_comments', $data_to_insert);
        $comments_list = $this->get_comment_list_by_id($data_to_insert['article_id']);
        return $comments_list;
    }


}